//引入mock模块
import Mock from 'mockjs'
// import './demo.js'

/**********   mock拦截请求     *************/
//定义get请求
Mock.mock('api/get/news', 'get', () => {
	return {
		status: 200,
		message: '获取数据成功',
		data: Mock.mock({
			'list|50-99': [
				{
					name: '@cname',
					address: '@city(true)',
					id: '@increment()',
				},
			],
		}),
	}
})
//定义post请求
Mock.mock('api/post/news', 'post', () => {
	return {
		status: 200,
		message: '获取数据成功',
	}
})

// ==================        demo
const { newsList } = Mock.mock({
	'newsList|75': [
		{
			id: '@increment',
			title: '@ctitle()',
			content: '@cparagraph(5,10)',
			img_url: "@image('50*50','#f2f2f2','#999999','png','mono')",
			add_time: '@date(yyyy-MM-dd hh:mm:ss)',
		},
	],
})
//从url中获取pageindex，pagesize
var getQuery = (url, name) => {
	const index = url.indexOf('?')
	if (index !== -1) {
		const queryStrArr = url.substr(index + 1).split('&')
		for (var i = 0; i < queryStrArr.length; i++) {
			const itemArr = queryStrArr[i].split('=')
			if (itemArr[0] === name) {
				return itemArr[1]
			}
		}
	}
	return null
}

/* 
获取新闻列表
api/get/news?pageinde=1&pagesize=10
*/
//使用个正则匹配 get请求中的url ：即满足url中包含 api/get/news 的条件即可
Mock.mock(/\/api\/get\/news/, 'get', (options) => {
	// 获取传递参数pageindex，pagesize
	const pageindex = getQuery(options.url, 'pageindex')
	const pagesize = getQuery(options.url, 'pagesize')
	const start = (pageindex - 1) * pagesize
	const end = pagesize * pageindex
	const totalPage = Math.ceil(newsList.length / pagesize)

	//  pageindex:1 pagesize:10 返回0-9条数据  2-10-（10-19） 3-10（20-29）
	// 数据的起始位置：（pageindex-1）*pagesize 结束位置：pageindex*pagesize
	const list = pageindex > totalPage ? [] : newsList.slice(start, end)
	return {
		status: 200,
		message: '获取新闻列表成功',
		list: list,
		total: totalPage,
	}
})

/* 
添加新闻
*/
Mock.mock('/api/add/news', 'post', (options) => {
	const body = JSON.parse(options.body)
	newsList.push(
		Mock.mock({
			id: '@increment',
			title: body.title,
			content: body.content,
			img_url: "@image('50*50','#FF83FA','#FCFCFC','png','mono')",
			add_time: '@date(yyyy-MM-dd hh:mm:ss)',
		})
	)
	return {
		status: 200,
		message: '添加成功',
		list: newsList,
		total: newsList.length,
	}
})

/* 
删除新闻
*/
Mock.mock('/api/delete/news', 'post', (options) => {
	const body = JSON.parse(options.body)
	const index = newsList.findIndex((item) => {
		return item.id === body.id
	})
	newsList.splice(index, 1)
	return {
		status: 200,
		message: '删除成功',
		list: newsList,
		total: newsList.length,
	}
})
